package br.com.timecardforpeon.domain;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import br.com.timecardforpeon.util.Util;

public class EntryPerDay {

	private Day day;
	private List<Entry> entries;
	
	public EntryPerDay(Day day) {
		super();
		
		if (day == null || day.getId() == -1) {
			throw new RuntimeException("'Day' cannot be null or transient object");
		}
		
		this.day = day;
		this.entries = new LinkedList<Entry>();
	}

	public EntryPerDay addEntry(Entry entry) {
		
		this.entries.add(entry);
		return this;
	}
	
	public EntryPerDay removeEntry(Entry entry) {
		
		this.entries.remove(entry);
		return this;
	}

	public EntryPerDay removeEntry(int index) {
		
		this.entries.remove(index);
		return this;
	}
	
	public int getTotalMinutes() {
		
		int totalMinutes = 0;
		for (Entry entry : entries) {
			totalMinutes += entry.getTotalMinutes();
		}
		
		return totalMinutes;
	}
	
	public String getTotalHours() {
		
		return Util.getTotalHours(this.getTotalMinutes());
	}
	
	public List<Entry> getEntries() {
		return Collections.unmodifiableList(this.entries);
	}
	
	public String createCsv(int maxEntries) {
		
		StringBuilder sb = new StringBuilder();
		sb
			.append(this.day.toString())
			.append(";");
		
		int count = 0;
		for (Entry entry : this.entries) {
			sb.append(entry.toString());
			count++;
		}
		
		for (int i = count; i < maxEntries; i++) {
			sb
				.append(";")
				.append(";");
		}
		
		return sb
				.append(this.getTotalHours())
				.append(";")
				.append(this.day.getNotes())
				.append(";")
				.toString();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((day == null) ? 0 : day.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		EntryPerDay other = (EntryPerDay) obj;
		if (day == null) {
			if (other.day != null)
				return false;
		} else if (!day.equals(other.day))
			return false;
		return true;
	}
}